package com.mapbar.ure.backend;

/**
 * NFA的实现
 * 
 * @author QIN Jian
 * 
 * @param <T>
 */
public class NFA<T> {
	NFANode<T> start;
	NFANode<T> end;

	public NFA(T value) {
		start = new NFANode<T>();
		end = new NFANode<T>();
		start.addNext(value, end);
	}

	public NFANode<T> getStart() {
		return start;
	}

	public NFANode<T> getEnd() {
		return end;
	}

	public NFA<T> cons(NFA<T> node1) {
		end.addNext(null, node1.start);
		end = node1.end;
		return this;
	}

	public NFA<T> or(NFA<T> node) {
		NFANode<T> s = new NFANode<T>();
		NFANode<T> e = new NFANode<T>();

		s.addNext(null, node.start);
		s.addNext(null, this.start);
		node.end.addNext(null, e);
		this.end.addNext(null, e);

		start = s;
		end = e;
		return this;
	}

	public NFA<T> closure() {
		NFANode<T> s = new NFANode<T>();
		NFANode<T> e = new NFANode<T>();

		end.addNext(null, start);
		s.addNext(null, e);
		s.addNext(null, start);
		end.addNext(null, e);

		start = s;
		end = e;
		return this;
	}
}
